﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Marmat.Forms.Skin
{
    [Editor("Marmat.Forms.Skin.Design.CollectionEditor", typeof(UITypeEditor))]
    public class ControlItemCollection<T> : IList<T>, IList
    {
        internal Control control;
        private List<T> _list = new List<T>();
        public ControlItemCollection(Control control)
        {
            this.control = control;
        }

        public T this[int index] { get => _list[index]; set => _list[index] = value; }

        public int Count => _list.Count;

        public bool IsReadOnly => false;

        public bool IsFixedSize => ((IList)_list).IsFixedSize;

        public object SyncRoot => ((IList)_list).SyncRoot;

        public bool IsSynchronized => ((IList)_list).IsSynchronized;

        object IList.this[int index] { get => ((IList)_list)[index]; set => ((IList)_list)[index] = value; }

        public virtual void Add(T item)
        {
            this._list.Add(item);
            this.control.Invalidate();
        }

        public void Clear()
        {
            this._list.Clear();
        }

        public bool Contains(T item)
        {
            return this._list.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            this._list.CopyTo(array, arrayIndex);

        }

        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return this._list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._list.GetEnumerator();
        }

        public int IndexOf(T item)
        {
            return this._list.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            this._list.Insert(index, item);
        }

        public bool Remove(T item)
        {
            return this._list.Remove(item);
        }

        public void RemoveAt(int index)
        {
            this._list.RemoveAt(index);
        }

        int IList.Add(object value)
        {
            if (value is T item)
            {
                this.Add(item);
                return this.Count;
            }
            else
                throw new ArgumentException(nameof(value));
        }

        bool IList.Contains(object value)
        {
            return ((IList)_list).Contains(value);
        }

        int IList.IndexOf(object value)
        {
            return ((IList)_list).IndexOf(value);
        }

        void IList.Insert(int index, object value)
        {
            ((IList)_list).Insert(index, value);
        }

        void IList.Remove(object value)
        {
            ((IList)_list).Remove(value);
        }

        void ICollection.CopyTo(Array array, int index)
        {
            ((IList)_list).CopyTo(array, index);
        }
    }
}
